/*
TrueType Fonts Quick Installer (aka "ttfqi") lets you quickly install TTF fonts
on your computer!
Version: 1.0
Written by nokoru

un-licensed, proudly free and open source work, see "LICENSE" <3
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

typedef enum {
	CACHE_UPDATE, CACHE_IGNORE
} cache_mode;

int main(int argc, char **argv) {
	int c=0;
	cache_mode cm=CACHE_UPDATE;

	if (argc == 1) {
		printf("Error: No options! Use ttfqi -h for help.\n");
		return 1;
	}
	//read options
	while((c = getopt(argc, argv, "uih")) != -1) {
		switch(c) {
		case 'u':
			cm=CACHE_UPDATE;
			goto install;
		case 'i':
			cm=CACHE_IGNORE;
			goto install;
		case 'h':
			goto help;
		default:
			return 1;
		}
	}

	install:
	//check if root
	if (setuid(0) == -1) {
		printf("You must be root to do that.\n");
		return 1;
	}
	//check if no files
	if (argc <= 2) {
		printf("Error: No input files. Please type the filenames of the fonts you want to install.\n");
		return 1;
	}
	int i=0;
	//validate files
	printf("Checking files...\n");
	for(i=2; i<argc; i++) {
		//check if file exists
		if (access(argv[i], F_OK) == -1) {
			printf("Error: File \"%s\" doesn't exist! (Aborted.)\n", argv[i]);
			return 1;
		}
		//check if file is a TTF font
		char *ext;
		if ((ext = strrchr(argv[i], '.')) != NULL) {
			if (strcmp(ext, ".ttf") != 0 && strcmp(ext, ".TTF") != 0) {
				printf("Error: File \"%s\" is not a TrueType font! (Aborted.)\n", argv[i]);
				return 1;
			}
		} else {
			printf("Error: File \"%s\" is not a TrueType font! (Aborted.)\n", argv[i]);
			return 1;
		}
	}
	//Files ok, move font files to /usr/local/share/fonts/
	printf("Files OK. Moving fonts...\n");
	for(i=2; i<argc; i++) {
		char newfname[24 + strlen(argv[i])];
	 	sprintf(newfname,"/usr/local/share/fonts/%s", argv[i]);
		if (rename(argv[i], newfname) == -1) {
			printf("Error: Oops! Error while moving font files (Aborted.)\n");
			return 1;
		}
	}
	if (cm == CACHE_UPDATE) {
		printf("Installed %d font(s). Updating cache...\n", argc-2);
		system("fc-cache -f");
		printf("Cache updated.\n");
		printf("OK.\n");
		return 0;
	} else {
		printf("Installed %d font(s). Please reboot your system or use fc-cache -f\n", argc-2);
		printf("OK.\n");
		return 0;
	}

	help:
	printf("--- TrueType Fonts Quick Installer (aka ttfqi) ---\n");
	printf("Author: nokoru <nokoru@disroot.org>  Version: 1.0\n");
	printf("\nUsage: ttfqi <options> [<file(s)>]\nOptions:\n");
	printf("-u\tInstall fonts and update font cache.\n-i\tInstall fonts without updating font cache (you'll need to reboot your system.)\n-h\tShow this information.\n\nttfqi is proudly FOSS and un-licensed; see LICENSE!.\n\nThank you for using ttfqi <3!\n");
	return 0;
}
